#include "speexEC.h"

CSpeexEC::CSpeexEC()
{
	m_bHasInit = false;
	m_pState = NULL;
	m_pPreprocessorState = NULL;
	m_nFrameSize = 220;
	m_nFilterLen = 220*8;
	m_nSampleRate = 16000;
	m_pfNoise = NULL;
}

CSpeexEC::~CSpeexEC()
{
	Reset();
}

void CSpeexEC::Init(int frame_size, int filter_length, int sampling_rate)
{
	Reset(); 

	if (frame_size<=0 || filter_length<=0 || sampling_rate<=0)
	{
		m_nFrameSize = 220;
		m_nFilterLen = 220*8;
		m_nSampleRate = 16000;
	}
	else
	{
		m_nFrameSize =frame_size;
		m_nFilterLen = filter_length;
		m_nSampleRate = sampling_rate;
	}

	m_pState = speex_echo_state_init(m_nFrameSize, m_nFilterLen);
	m_pPreprocessorState = speex_preprocess_state_init(m_nFrameSize, m_nSampleRate);
	m_pfNoise = new float[m_nFrameSize+1];
	m_bHasInit = true;
}

void CSpeexEC::Reset()
{
	if (m_pState != NULL)
	{
		speex_echo_state_destroy(m_pState);
		m_pState = NULL;
	}
	
	if (m_pPreprocessorState != NULL)
	{
		speex_preprocess_state_destroy(m_pPreprocessorState);
		m_pPreprocessorState = NULL;
	}
	
	if (m_pfNoise != NULL)
	{
		delete []m_pfNoise;
		m_pfNoise = NULL;
	}
	m_bHasInit = false;
}

void CSpeexEC::DoAEC(short* mic, short* ref, short* out)
{
	if (!m_bHasInit)
		return;

	printf("m_nFrameSize=%d, m_nFilterLen=%d, m_nSampleRate=%d\n", m_nFrameSize, m_nFilterLen, m_nSampleRate);
	speex_echo_cancel(m_pState, mic, ref, out, (spx_int32_t*)m_pfNoise);
	speex_preprocess(m_pPreprocessorState, (spx_int16_t *)out, (spx_int32_t*)m_pfNoise);
}
